#include "SerialPortQt.h"


SerialPortQt::SerialPortQt(const std::string devName, QObject *parent)
    :CommBaseQt(parent),
      m_portSer(this)
{
    m_portSer.setPortName(devName.c_str());
}

SerialPortQt::~SerialPortQt()
{
    printf("SerialPortQt derived() is called! Then close m_portSer\n");
    Close();
}

//bool SerialPortQt::Open()
//{
//    return m_port.open(QIODevice::ReadWrite);
//}

bool SerialPortQt::SetOpt(qint32 baudRate, QSerialPort::FlowControl flowControl,QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits, QSerialPort::Parity parity)
{
    //    m_portSer.setPortName(m_devName.c_str());
    //    serialport.setPortName("/dev/ttymxc3");
    if(Open())
    {
        //设置波特率
        if(!m_portSer.setBaudRate(baudRate))
        {
            return false;
        }
        //设置数据位
        if(!m_portSer.setDataBits(dataBits))
        {
            return false;
        }
        //设置校验位
        if(!m_portSer.setParity(parity))
        {
            return false;
        }
        //设置流控制
        if(!m_portSer.setFlowControl(flowControl))
        {
            return false;
        }
        //设置停止位
        if(!m_portSer.setStopBits(stopBits))
        {
            return false;
        }
    }
    return true;
}

bool SerialPortQt::Open()
{
    return m_portSer.open(QIODevice::ReadWrite);
}

int SerialPortQt::Send(const unsigned char *sendBuf,const int dataLen)
{
    return m_portSer.write((char*)sendBuf, dataLen);

    //    QMetaObject::invokeMethod(&m_portSer,"write",Q_ARG(aaa,dataLen));
}

void SerialPortQt::Close()
{
    if(m_portSer.isOpen())
    {
        m_portSer.close();
    }
}

int SerialPortQt::Read(unsigned char *readbuf, const int dataLen)
{    
    int ret = m_portSer.read((char*)readbuf,dataLen);
    return ret;
}

